package com.laomuji.android.mvvm.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.util.AttributeSet
import android.widget.FrameLayout
import androidx.core.content.withStyledAttributes
import com.laomuji.android.mvvm.R

/**
 * 中心是一块透明区域的FrameLayout
 * @author laomuji666
 * @since 2024/2/21
 */
class TransplantCenterFrameLayout : FrameLayout{
    private var mBackgroundPaint: Paint? = null
    private var maskColor = 0
    private var radius = 0

    constructor(context: Context) : this(context,null)

    constructor(context: Context,attrs:AttributeSet?) : super(context,attrs){
        init()
        if(attrs!=null){
            initAttr(context, attrs)
        }
    }

    private fun init() {
        setWillNotDraw(false)
        setLayerType(LAYER_TYPE_HARDWARE, null)
        mBackgroundPaint = Paint()
        mBackgroundPaint!!.setXfermode(PorterDuffXfermode(PorterDuff.Mode.CLEAR))
    }

    private fun initAttr(context: Context, attrs: AttributeSet) {
        context.withStyledAttributes(attrs, R.styleable.TransplantCenterFrameLayout) {
            maskColor =
                getColor(R.styleable.TransplantCenterFrameLayout_tcflMaskColor, Color.TRANSPARENT)
            radius = getDimensionPixelSize(R.styleable.TransplantCenterFrameLayout_tcflRadius, 0)
        }
    }

    override fun onDraw(canvas: Canvas) {
        canvas.drawColor(maskColor)
        val x = width / 2f
        val y = height / 2f
        if (x >= 0 && y >= 0) {
            canvas.drawCircle(x, y, radius.toFloat(), mBackgroundPaint!!)
        }
    }
}

